<template>
  <div class="book-detail-container">
    <el-button
        type="text"
        icon="el-icon-arrow-left"
        class="back-button"
        @click="$router.go(-1)"
    >
      返回书单
    </el-button>

    <div class="detail-content">
      <!-- 书籍封面区 -->
      <div class="cover-section">
        <el-image
            :src="book.cover"
            :preview-src-list="[book.cover]"
            fit="contain"
            class="main-cover"
        >
          <div slot="error" class="cover-error">
            <i class="el-icon-picture-outline"></i>
            <p>封面加载失败</p>
          </div>
        </el-image>
      </div>

      <!-- 书籍信息区 -->
      <div class="info-section">
        <h1 class="book-title">{{ book.title }}</h1>
        <div class="meta-info">
          <p class="author">作者：{{ book.author }}</p>
          <p class="isbn">ISBN：{{ book.isbn || '暂无数据' }}</p>
        </div>

        <div class="price-section">
          <span class="current-price">¥{{ book.price.toFixed(1) }}</span>
          <span class="original-price" v-if="book.originalPrice">
            ¥{{ book.originalPrice.toFixed(1) }}
          </span>
        </div>

        <div class="action-buttons">
          <el-button
              type="danger"
              size="medium"
              :disabled="book.stock <= 0"
              @click="handlePurchase"
          >
            <i class="el-icon-shopping-bag-1"></i>
            立即购买
          </el-button>
          <el-button
              type="primary"
              size="medium"
              @click="addToCart(book)"
          >
            <i class="el-icon-shopping-cart-2"></i>
            加入购物车
          </el-button>
        </div>

        <div class="button-group">
          <el-button
            type="success"
            size="small"
            @click="goToBookReviews(book)"
            class="review-btn"
            :class="{ 'is-clicked': isReviewClicked }"
          >
            <i class="el-icon-chat-line-round"></i>
            <span class="btn-text">评论</span>
          </el-button>
        </div>

        <div class="detail-section">
          <h3 class="section-title">图书详情</h3>
          <div class="detail-content">
            <p class="stock">库存状态：{{ book.stock > 0 ? `有货（剩余${book.stock}本）` : '暂时缺货' }}</p>
            <p class="publisher">出版社：{{ book.publisher || '未知出版社' }}</p>
            <p class="publish-date">出版日期：{{ book.publishDate || '未知日期' }}</p>
            <p class="pages">页数：{{ book.pages || '-' }}页</p>
          </div>
        </div>

        <div class="description-section">
          <h3 class="section-title">内容简介</h3>
          <div class="description-content">
            {{ book.description || '暂无内容简介' }}
          </div>
        </div>

        <!-- 评论模块 -->
        <div class="comment-section">
          <h3 class="section-title">读者评论（{{ comments.length }}）</h3>
          <div class="comment-editor">
            <el-input
                type="textarea"
                :rows="3"
                placeholder="写下你的阅读感受..."
                v-model="newComment"
                resize="none"
                :maxlength="500"
                show-word-limit
                class="comment-input"
            ></el-input>
            <div class="comment-action">
              <el-button
                  type="primary"
                  size="small"
                  @click="submitComment"
                  :disabled="!newComment.trim() || isSubmitting"
                  :loading="isSubmitting"
                  class="submit-btn"
              >
                <i class="el-icon-s-promotion"></i>
                发表评论
              </el-button>
            </div>
          </div>
          <div class="comment-list">
            <div
                class="comment-item"
                v-for="(comment, index) in comments"
                :key="index"
                :class="{ 'fade-in': true }"
            >
              <div class="comment-header">
                <div class="user-info">
                  <i class="el-icon-user-solid"></i>
                  <span class="username">{{ comment.user || '匿名用户' }}</span>
                </div>
                <span class="date">{{ comment.date }}</span>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-footer">
                <el-button 
                  type="text" 
                  size="mini" 
                  @click="likeComment(index)"
                  :class="{ 'is-liked': comment.liked }"
                >
                  <i :class="comment.liked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
                  {{ comment.likes || 0 }}
                </el-button>
                <el-button 
                  type="text" 
                  size="mini" 
                  @click="replyComment(index)"
                >
                  <i class="el-icon-chat-dot-round"></i>
                  回复
                </el-button>
              </div>
            </div>
            <div v-if="comments.length === 0" class="no-comment">
              <i class="el-icon-chat-line-round"></i>
              <p>暂时还没有评论，快来抢沙发吧~</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BookDetail',
  props: ['id'],
  data() {
    return {
      newComment: '',
      comments: JSON.parse(localStorage.getItem(`comments_${this.id}`)) || [],
      isSubmitting: false,
      isReviewClicked: false
    };
  },
  computed: {
    book() {
      const bookId = Number(this.$route.query.id);
      return this.$store.state.books.find(b => b.id === bookId) || {};
    }
  },
  methods: {
    handlePurchase() {
      if (!this.$store.state.user) {
        this.$message.warning('请先登录');
        this.$router.push({
          path: '/login',
          query: { redirect: this.$route.fullPath }
        });
        return;
      }

      if (this.book.stock <= 0) {
        this.$message.error('当前书籍已售罄');
        return;
      }

      this.$confirm(`确定要购买《${this.book.title}》吗？`, '确认购买', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际开发中应调用购买接口
        this.$message.success('购买成功！');
        this.book.stock--;
      }).catch(() => {});
    },

    async addToCart(book) {
      if (!this.$store.state.user) {
        this.$message.warning('请先登录');
        this.$router.push({
          path: '/login',
          query: { redirect: this.$route.fullPath }
        });
        return;
      }

      if (book.stock <= 0) {
        this.$message.error('该商品已售罄');
        return;
      }

      try {
        await this.$store.dispatch('addToCart', book);
        this.$message.success(`已添加《${book.title}》到购物车`);
      } catch (error) {
        this.$message.warning(error);
      }
    },

    async submitComment() {
      if (!this.$store.state.user) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }

      if (!this.newComment.trim()) {
        this.$message.warning('评论内容不能为空');
        return;
      }

      this.isSubmitting = true;
      try {
        const comment = {
          content: this.newComment.trim(),
          date: new Date().toLocaleString(),
          user: this.$store.state.user.username,
          likes: 0,
          liked: false
        };

        this.comments.unshift(comment);
        localStorage.setItem(`comments_${this.id}`, JSON.stringify(this.comments));
        this.newComment = '';
        this.$message.success('评论发表成功');
      } catch (error) {
        this.$message.error('评论发表失败，请重试');
      } finally {
        this.isSubmitting = false;
      }
    },

    likeComment(index) {
      if (!this.$store.state.user) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }

      const comment = this.comments[index];
      comment.liked = !comment.liked;
      comment.likes = comment.liked ? (comment.likes || 0) + 1 : (comment.likes || 1) - 1;
      localStorage.setItem(`comments_${this.id}`, JSON.stringify(this.comments));
    },

    replyComment(index) {
      if (!this.$store.state.user) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }

      const comment = this.comments[index];
      this.newComment = `@${comment.user} `;
      this.$nextTick(() => {
        document.querySelector('.comment-input textarea').focus();
      });
    },

    goToBookReviews(book) {
      if (this.isReviewClicked) return;
      
      if (!this.$store.state.user) {
        this.$message.warning('请先登录');
        this.$router.push({ path: '/login', query: { redirect: '/reviews', bookId: book.id } });
        return;
      }

      this.isReviewClicked = true;
      setTimeout(() => {
        this.isReviewClicked = false;
        this.$router.push({ path: '/reviews', query: { bookId: book.id } });
      }, 300);
    }
  }
};
</script>

<style scoped>
.book-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.back-button {
  margin-bottom: 20px;
  color: #666;
  padding-left: 0;
}

.back-button:hover {
  color: #6a11cb;
}

.detail-content {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 40px;
}

.main-cover {
  width: 100%;
  height: 500px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.cover-error {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  background: #f5f7fa;
}

.book-title {
  font-size: 2.2rem;
  color: #303133;
  margin-bottom: 15px;
}

.meta-info {
  margin-bottom: 25px;
  color: #606266;
}

.price-section {
  margin: 30px 0;
}

.current-price {
  font-size: 2rem;
  color: #f56c6c;
  margin-right: 15px;
}

.original-price {
  font-size: 1.2rem;
  color: #909399;
  text-decoration: line-through;
}

.action-buttons {
  margin: 40px 0;
  display: flex;
  gap: 20px;
}

.button-group {
  margin: 40px 0;
  display: flex;
  justify-content: flex-end;
}

.detail-section, .description-section, .comment-section {
  margin: 40px 0;
  padding: 25px;
  background: #f8f9fa;
  border-radius: 8px;
}

.section-title {
  font-size: 1.4rem;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e4e7ed;
}

.description-content {
  line-height: 1.8;
  color: #606266;
}

.comment-editor {
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.comment-input {
  margin-bottom: 15px;
}

.comment-action {
  display: flex;
  justify-content: flex-end;
}

.submit-btn {
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.comment-item {
  padding: 20px;
  margin: 15px 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  animation: fadeIn 0.5s ease;
}

.comment-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-info i {
  color: #409EFF;
  font-size: 18px;
}

.username {
  font-weight: 600;
  color: #303133;
}

.date {
  color: #909399;
  font-size: 0.9rem;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 15px;
  white-space: pre-wrap;
}

.comment-footer {
  display: flex;
  gap: 15px;
  border-top: 1px solid #ebeef5;
  padding-top: 12px;
}

.comment-footer .el-button {
  padding: 0;
  font-size: 0.9rem;
}

.comment-footer .el-button i {
  margin-right: 4px;
}

.is-liked {
  color: #e6a23c !important;
}

.no-comment {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.no-comment i {
  font-size: 48px;
  margin-bottom: 15px;
  color: #dcdfe6;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in {
  animation: fadeIn 0.5s ease;
}

.review-btn {
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  background: linear-gradient(45deg, #67c23a 0%, #85ce61 100%);
  border: none;
  color: white;
}

.review-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.2);
}

.review-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(103, 194, 58, 0.1);
}

.review-btn.is-clicked {
  transform: scale(0.95);
  animation: reviewPulse 0.3s ease;
}

.review-btn i {
  margin-right: 4px;
  transition: all 0.3s ease;
}

.review-btn.is-clicked i {
  transform: scale(1.2);
}

.review-btn::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 5px;
  height: 5px;
  background: rgba(255, 255, 255, 0.5);
  opacity: 0;
  border-radius: 100%;
  transform: scale(1, 1) translate(-50%);
  transform-origin: 50% 50%;
}

.review-btn.is-clicked::after {
  animation: ripple 0.6s ease-out;
}

@keyframes reviewPulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.9);
  }
  100% {
    transform: scale(0.95);
  }
}

.review-btn .btn-text {
  display: inline-block;
  transition: all 0.3s ease;
}

.review-btn.is-clicked .btn-text {
  transform: scale(0.9);
}

@media (max-width: 768px) {
  .detail-content {
    grid-template-columns: 1fr;
  }

  .main-cover {
    height: 400px;
  }

  .book-title {
    font-size: 1.8rem;
  }

  .action-buttons {
    flex-direction: column;
  }

  .button-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .el-button {
    width: 100%;
    margin: 5px 0;
  }
  
  .review-btn {
    min-width: 100%;
  }
}
</style>